package yagwl.service.util;

import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import yagwl.service.util.svc.BaseException;
import yagwl.service.util.svc.BaseException.ErrorCode;

public class NumberUtil {

  private static Map<Locale, NumberFormat> numberInstanceMap = new HashMap<Locale, NumberFormat>();
  private static Map<Locale, NumberFormat> currencyInstanceMap = new HashMap<Locale, NumberFormat>();

  public static String toCurrencyString(float number, Locale locale) {
    NumberFormat nf = currencyInstanceMap.get(locale);
    if (nf == null) {
      nf = NumberFormat.getCurrencyInstance(locale);
      currencyInstanceMap.put(locale, nf);
    }
    return nf.format(number);
  }

  public static String toString(float number, Locale locale) {
    NumberFormat nf = numberInstanceMap.get(locale);
    if (nf == null) {
      nf = NumberFormat.getNumberInstance(locale);
      nf.setMaximumFractionDigits(2);
      nf.setMinimumFractionDigits(2);
      numberInstanceMap.put(locale, nf);
    }
    return nf.format(number);
  }

  public static float toFloatValue(String number) {
    try {
      return Float.valueOf(number.trim()).floatValue();
    } catch (NumberFormatException e) {
      throw new BaseException(ErrorCode.INVALID_NUMBER);
    }
  }
  
  public static String toString(long number, char partSeparator,
      int... partLengths) {
    int numLength = 0;
    for (long temp = number; temp != 0; numLength++)
      temp /= 10;
    String idStr = Long.toString(number);
    StringBuffer pretty = new StringBuffer();
    for (int partLength : partLengths) {
      if (idStr.length() <= partLength) {
        pretty.append(idStr);
        return pretty.toString();
      }
      pretty.append(idStr.substring(0, partLength) + partSeparator);
      idStr = idStr.substring(partLength);
    }
    pretty.append(idStr);
    return (pretty.toString());
  }

}
